package sitar.controllers;
import oboe.core.SigSlot;
import php.db.Connection;
import php.db.Mysql;
import php.db.ResultSet;

/**
 * ...
 * @author Felipe Manga
 */

class Database extends SigSlot
{
	var cnx:Connection;
	
	public function new( args:Dynamic ) 
	{
		super();
		this.cnx = Mysql.connect( args );
	}
	
	public function query(str:String, subst:Array<Dynamic>=null ):ResultSet
	{
		if ( subst != null )
		{
			for ( i in 0 ... subst.length )
			{
				var val:Dynamic = subst[i];
				
				if ( !Std.is( val, Int ) && !Std.is( val, Float ) )
				{
					val = Std.string(val);
				}
				
				if ( Std.is( val, String ) )
				{
					val = "'" + this.cnx.escape(val) + "'";
				}
				
				str = str.split("%" + i).join( Std.string(val) );
			}
		}
		
		return this.cnx.request( str );
	}
	
	@slot function onShutdown():Void
	{
		this.cnx.close();
	}
	
}